<?php
/**
 * Controller that handles login/logout actions
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Usermanagement Module
 * @subpackage Controller
 * @license  New BSD License
 *
 */
class usermanagement_AuthController extends Bel_Controller {
	
	/**
	 * Auth Object
	 *
	 * @var Models_Usermanagement_Auth
	 */
	private $_auth;

	/**
	 * Initialization
	 *
	 */
	function init() {
		$this->_auth = Models_Usermanagement_Auth::getInstance ();
		parent::init ();
	}
	
	/**
	 * Shows login form in case an user is not logged in, in the other case displays logout block 
	 *
	 */
	public function loginformAction() {
		if (! $this->_auth->isLoggedIn ()) {
			//$this->view->assign('messages',$this->_messages->getMessages());
			$this->view->display ( 'usermanagement/auth/loginform.tpl' );
		} else {
			$this->view->assign ( 'userdata', $this->_auth->getUserSession () );
			$this->view->display ( 'usermanagement/auth/logout.tpl' );
		}
	}
	
	/**
	 * Runs when user is not allowed to access to a resource
	 *
	 */
	public function forbiddenAction() {
		$this->view->display ( 'usermanagement/auth/forbidden.tpl' );
	}
	
	/**
	 * Logouts user
	 *
	 */
	public function logoutAction() {
		$this->_auth->logout ();
		$redirectUrl = ($this->_request->getModuleName()=='admin')?'/admin':'/';
		$this->_redirect ( $redirectUrl );
	}
	
	/**
	 * Login action
	 *
	 */
	public function loginAction() {
		
		$redirectUrl = ($this->_request->getModuleName()=='admin')?'/admin':'/';
		
		if (! $this->_request->getParam ( 'username' )) {
			$this->_redirect ( $redirectUrl );
		}

		$result = $this->_auth->login ( (string)$this->_request->getParam ( 'username' ), (string)$this->_request->getParam ( 'password' ) );
		switch ( $result->getCode ()) {
			case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
				$this->_messages->setMessage ( 'Username was not found', 'error' );
			break;
			case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID :
				$this->_messages->setMessage ( "Login failed! Wrong credentials or your account is not active", 'error' );
			break;
			case Zend_Auth_Result::SUCCESS :
				$this->_auth->setUserSession ();
				$this->_messages->setMessage ( "Welcome" );
			break;
		}
		$this->_redirect ( $redirectUrl );
	}
}